<template>
  <Wrapper>
    <el-button
      type="primary"
      :disabled="!selectList.length"
      @click="handleExport"
      >导出已选择</el-button
    >

    <data-table
      :data="list"
      :columns="[
        { label: '姓名', prop: 'name' },
        { label: '年龄', slot: 'age' },
        { label: '地址', prop: 'address' },
        { label: '说明', prop: 'desc' },
      ]"
      show-selection
      style="margin-top: 22px"
      @select="handleSelect"
    >
      <template #age="{ item }">
        <el-tag type="primary">{{ item.age }}</el-tag>
      </template>
    </data-table>
  </Wrapper>
</template>

<script setup>
import { parseTime } from '@/utils/utils'
import DataTable from '@/components/table'
import useForm from '@/hooks/useForm'

const { formData } = useForm({
  filename: 'export-excel',
  autoWidth: true,
  bookType: 'xlsx',
})

const loading = ref(false)
const selectList = ref([])
const list = [
  { name: '张三', age: 18, address: '北京', desc: '11' },
  { name: '李四', age: 20, address: '上海', desc: '1111111111' },
  { name: '王五', age: 22, address: '广州', desc: '11111' },
  { name: '赵六', age: 24, address: '深圳', desc: '111' },
  { name: '钱七', age: 26, address: '杭州', desc: '1111111111111' },
  { name: '孙八', age: 28, address: '成都', desc: '1111111' },
  { name: '周九', age: 30, address: '重庆', desc: '111111' },
  { name: '吴十', age: 32, address: '武汉', desc: '11111111' },
]

function handleExport() {
  loading.value = true
  import('@/plugins/export-excel').then((excel) => {
    const tHeader = ['姓名', '年龄', '地址', '说明']
    const filterVal = ['name', 'age', 'address', 'desc']
    const data = formatJson(filterVal, selectList.value)

    excel.export_json_to_excel({
      header: tHeader,
      data,
      ...formData.value,
    })
    loading.value = false
  })
}

function handleSelect(val) {
  selectList.value = val
}

function formatJson(filterVal, jsonData) {
  return jsonData.map((v) =>
    filterVal.map((j) => {
      if (j === 'timestamp') {
        return parseTime(v[j])
      } else {
        return v[j]
      }
    }),
  )
}
</script>
